package org.filetransfer.file_transfer_java_backend.service;
import org.filetransfer.file_transfer_java_backend.model.FileCategoryModel;
import org.filetransfer.file_transfer_java_backend.model.ServiceFileInfoModel;
import org.filetransfer.file_transfer_java_backend.repository.FileRepository;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.*;
@Service
public class FileService {
    private final FileRepository fileRepository;
    private final FileUploadService fileUploadService;
    //    public List<File> getFilesByShareItem(Long shareItemId) {
//        return fileRepository.findByShareItem_Id(shareItemId);
//    }
    public FileService(FileRepository fileRepository, FileUploadService fileUploadService) {
        this.fileRepository = fileRepository;
        this.fileUploadService = fileUploadService;
    }    public Optional<ServiceFileInfoModel> getStatistics(Integer dayOfBefore) {
        if (dayOfBefore == null) {
            return fileRepository.getStatistics();
        } else {
            var now = Instant.now();
            var end = now.minusSeconds(dayOfBefore * 24 * 60 * 60);
            var start = end.minusSeconds(24 * 60 * 60);
            return fileRepository.getStatisticsInRange(start, end);
        }
    }
    
    public Optional<ServiceFileInfoModel> getStatisticsByUser(Integer dayOfBefore, Long userId) {
        if (dayOfBefore == null) {
            return fileRepository.getStatisticsByUser(userId);
        } else {
            var now = Instant.now();
            var end = now.minusSeconds(dayOfBefore * 24 * 60 * 60);
            var start = end.minusSeconds(24 * 60 * 60);
            return fileRepository.getStatisticsInRangeByUser(start, end, userId);
        }
    }
    //    public List<FileCategoryModel> getFileCategoryStatistics() {
//        var items = fileRepository.getFileCategoryStatistics();
//        Map<FileCategoryModel.FileType, FileCategoryModel>
//                result = new Hashtable<>();
//        for (var item : items) {
//            if (result.get(item.getFileType()) == null) {
//                result.put(item.getFileType(), item);
//            } else {
//                var oldItem = result.get(item.getFileType());
//                oldItem.setFileCount(oldItem.getFileCount() + item.getFileCount());
//                oldItem.setTotalSize(oldItem.getTotalSize() + item.getTotalSize());
//            }
//        }
//        return new ArrayList<>(result.values());
//    }
    public List<FileCategoryModel> getFileCategoryStatistics() {
        var fileDetails = fileRepository.getFileDetails();
        Map<FileCategoryModel.FileType, FileCategoryModel> result = new HashMap<>();
        for (Object[] fileDetail : fileDetails) {
            String fileName = (String) fileDetail[0];
            long fileSize = (long) fileDetail[1];
            FileCategoryModel.FileType fileType = determineFileType(fileName);
            result.compute(fileType, (key, value) -> {
                if (value == null) {
                    return new FileCategoryModel(fileType, 1L, fileSize);
                } else {
                    value.setFileCount(value.getFileCount() + 1);
                    value.setTotalSize(value.getTotalSize() + fileSize);
                    return value;
                }
            });
        }
        return new ArrayList<>(result.values());
    }
    
    public List<FileCategoryModel> getFileCategoryStatisticsByUser(Long userId) {
        var fileDetails = fileRepository.getFileDetailsByUser(userId);
        Map<FileCategoryModel.FileType, FileCategoryModel> result = new HashMap<>();
        for (Object[] fileDetail : fileDetails) {
            String fileName = (String) fileDetail[0];
            long fileSize = (long) fileDetail[1];
            FileCategoryModel.FileType fileType = determineFileType(fileName);
            result.compute(fileType, (key, value) -> {
                if (value == null) {
                    return new FileCategoryModel(fileType, 1L, fileSize);
                } else {
                    value.setFileCount(value.getFileCount() + 1);
                    value.setTotalSize(value.getTotalSize() + fileSize);
                    return value;
                }
            });
        }
        return new ArrayList<>(result.values());
    }
    private FileCategoryModel.FileType determineFileType(String fileName) {
        String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        return switch (ext) {
            case "jpg", "jpeg", "png", "gif", "bmp", "webp" -> FileCategoryModel.FileType.IMAGE;
            case "mp4", "avi", "mov", "wmv", "flv", "mkv", "rmvb", "rm", "3gp", "mpg", "mpeg", "vob", "webm" ->
                    FileCategoryModel.FileType.VIDEO;
            case "mp3", "wav", "flac", "ape", "wma", "aac", "ogg", "m4a" -> FileCategoryModel.FileType.AUDIO;
            case "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "txt", "md", "html", "htm", "xml", "json", "csv",
                 "log" -> FileCategoryModel.FileType.DOCUMENT;
            default -> FileCategoryModel.FileType.OTHER;
        };
    }
}
